package io.naturecloud;

import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.io.*;
import java.util.Iterator;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;

public class UploadVideo extends HttpServlet {

    private String message;
    private String savePath;
    private ServletContext servletContext ;
    private static final Log log = LogFactory.getLog(UploadVideo.class);
    @Override
    public void init(ServletConfig config) throws ServletException
    {
        message = "hello world";
        servletContext = config.getServletContext();
        savePath = config.getInitParameter("fileUploadPath"); /*"D:\\work\\java_proj\\uploaddemo\\upload";*/
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.write("<h1>" + message + "</h1>");
        destroy();
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //super.doPost(req, resp);
        request.setCharacterEncoding("UTF-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //upload.setSizeMax(1024*1024);

        // Create a progress listener
        ProgressListener progressListener = new ProgressListener()
        {
            private long megaBytes = -1;

            /**
             * pBytesRead: The total number of bytes, which have been read so
             * far pContentLength: The total number of bytes, which are being
             * read. May be -1, if this number is unknown. pItems : The number
             * of the field, which is currently being read. (0 = no item so far,
             * 1 = first item is being read, ...)
             */
            public void update(long pBytesRead, long pContentLength, int pItems)
            {
                long mBytes = pBytesRead / 1000000;
                // "if" statement is for the purpose of reduce the progress
                // listeners activity
                // For example, you might emit a message only, if the number of
                // megabytes has changed:
                if (megaBytes == mBytes)
                {
                    return;
                }
                megaBytes = mBytes;
                System.out.println("We are currently reading item " + pItems);
                if (pContentLength == -1)
                {
                    System.out.println("So far, " + pBytesRead
                            + " bytes have been read.");
                } else
                {
                    System.out.println("So far, " + pBytesRead + " of "
                            + pContentLength + " bytes have been read.");
                }
            }
        };

        upload.setProgressListener(progressListener);


        try {
            List items = upload.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    System.out.println("表单参数名:" + item.getFieldName()
                            + "，表单参数值:" + item.getString("UTF-8"));
                } else {
                    if (item.getName() != null && !"".equals(item.getName())) {
                        System.out.println("上传文件的大小:" + item.getSize());
                        System.out.println("上传文件的类型:" + item.getContentType());
                        // item.getName()返回上传文件在客户端的完整路径名称
                        System.out.println("上传文件的名称:" + item.getName());

                        File tempFile = new File(item.getName());

                        // 上传文件的保存路径 //运行目录下
                        File file = new File(savePath,
                                tempFile.getName());
                        item.write(file);
                        request.setAttribute("upload.message", "上传文件成功！");
                    } else {
                        request.setAttribute("upload.message", "没有选择上传文件！");
                    }
                }
            }
        } catch (Exception e) {
            log.error("上传失败：",e);
            request.setAttribute("upload.message", "上传文件失败！");
        }
        request.getRequestDispatcher("/uploadResult.jsp").forward(request,
                response);
    }

    @Override
    public void destroy() {
        System.out.println("servlet销毁！");
        super.destroy();
    }

}
